import 'package:auto_size_text/auto_size_text.dart';
import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gongge/utils/CommUtils.dart';
import '../sqflite/DBManager.dart';
import '../utils/TimeUtils.dart';
import 'package:table_calendar/table_calendar.dart';
import '../config/AppConst.dart';
import '../utils/GamePageUtils.dart';
import '../utils/HelpUtils.dart';
import '../utils/SpUtils.dart';

//每日
class everyDay extends StatefulWidget {
  Widget setingWight;
  everyDay({
    Key? key,
    required this.setingWight,
  }) : super(key: key);

  @override
  State<everyDay> createState() => _MyWidgetState();
}

//已经完成的complist
List<DateTime> completeList = [];

class _MyWidgetState extends State<everyDay> {
  @override
  void initState() {
    //查询当月哪些完成了
    var dateTime = DateTime.now();
    //前面要补0 否则要出错
    String moth =
        dateTime.month < 10 ? "0${dateTime.month}" : '${dateTime.month}';

    String _time =
        "${dateTime.year}-${moth}-01 00:00:00.00000"; //注意格式不能有多余的空格 要补零，否则在DateTime.parse()时会报错
    var _strtimes = DateTime.parse(
        _time); //首先先将字符串格式的时间转为DateTime类型，因为millisecondsSinceEpoch方法转换要求为该格式

    //  var users = DBManager().getDBInfo(1);
    //    users.then((value) {
    // });

    DBManager().getDBChall(_strtimes.millisecondsSinceEpoch).then((value) {
      if (value.isNotEmpty) {
        for (var item in value) {
          completeList.add(DateTime.fromMillisecondsSinceEpoch(item.date));
        }
        setState(() {});
      }
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    double wight = CommUtils.getWidth(context);
    double hight = CommUtils.getHeight(context);
    return Column(
      children: [
        Container(
          height: hight * 0.65,
          child: Stack(
            children: [
              //日历
              Align(
                  alignment: Alignment.topCenter, child: getMin(wight, hight)),
              //设置 在这里否则点击无效
              Padding(
                padding: EdgeInsets.only(
                    left: 0, top: hight * 0.05, right: wight * 0.05, bottom: 0),
                child: Container(
                  height: hight * 0.05,
                  child: Stack(children: [
                    widget.setingWight,
                  ]),
                ),
              ), //设置
            ],
          ),
        ),

        // HelpUtils().getnewGame(context)

        //开始游戏
        Container(
          height: hight * 0.14,
          width: double.infinity,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/botton_day.png'),
              fit: BoxFit.fill,
            ),
          ),

           //测试
          // child: HelpUtils().getnewGame(
          //   context,
          //   callBack: ((selectIndex) {
          //     //  print("每日界面挑战成功了回调了");
          //     if (selectIndex == 1) {
          //       setState(() {});
          //     }
          //   }),
          // ),

          child: GamePageUtils().challengeComplete(false)
              ? Padding(
                  padding: EdgeInsets.only(
                      //  top: ScreenUtil().setHeight(size * 0.01),
                      left: wight * 0.2,
                      right: wight * 0.2),
                  child: HelpUtils().getcomplete(context),
                )
              : HelpUtils().getnewGame(
                  context,
                  callBack: ((selectIndex) {
                    //  print("每日界面挑战成功了回调了");
                    if (selectIndex == 1) {
                      setState(() {});
                    }
                  }),
                ),
        ),
      ],
    );
  }

//日历布局
  Widget getMin(double width, double height) {
    return Padding(
      padding: EdgeInsets.only(
        left: width * 0.03,
        right: width * 0.03,
      ),
      child: Stack(
        children: [
          Image.asset(
            'assets/images/bg_calendar.png',
            fit: BoxFit.fill,
            width: double.infinity,
            height: height * 0.65,
          ),
          Padding(
            padding: EdgeInsets.only(
                left: ScreenUtil().setWidth(width * 0.02),
                right: ScreenUtil().setWidth(width * 0.02),
                bottom: ScreenUtil().setHeight(height * 0.03)),
            child:
                Column(children: [Expanded(child: SizedBox()), getCalendar()]),
          ),
        ],
      ),
    );
  }

/**
 * 日历
 */
  Widget getCalendar() {
    double size = CommUtils.getHeight(context);
    //今日是否完成
    var todyComplete = GamePageUtils().challengeComplete(false);

    var dateTime = DateTime.now();
    var _strtimes =
        DateTime(dateTime.year, dateTime.month, dateTime.day, 0, 0, 0);
    //  var _intendtime = _strtimes .millisecondsSinceEpoch;//方法一
    print("zidsfs${_strtimes}");

    return Column(
      children: [
        AutoSizeText(
          //时间
          TimeUtils.gtTime(DateTime.now()),
          style: TextStyle(
            fontSize: ScreenUtil().setSp(16),
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
          maxLines: 1,
          textAlign: TextAlign.center,
          overflow: TextOverflow.ellipsis,
        ),
        SizedBox(
          //数越大，离下面星期就越远
          height: size * 0.05,
        ),
        TableCalendar(
          rowHeight: size * 0.053, //行高

          //星期设置
          daysOfWeekStyle: DaysOfWeekStyle(
            weekdayStyle: TextStyle(
                color: Color(0xffCBD2FF), fontSize: ScreenUtil().setSp(12)),
            //周末风格属性
            weekendStyle: TextStyle(
                color: Color(0xffCBD2FF), fontSize: ScreenUtil().setSp(12) //大小
                ),
          ),

          //日历数字设置
          calendarStyle: CalendarStyle(
            //周六，周日
            weekendTextStyle: TextStyle(
              color: Color(0xffCBD2FF),
            ),

            //工作日
            defaultTextStyle: TextStyle(
              color: Color(0xffCBD2FF),
            ),

            outsideDaysVisible: false, //隐藏不是当月的
            //今天的外边距
            cellMargin: EdgeInsets.only(left: 1, top: 1, bottom: 1, right: 1),
            todayDecoration: BoxDecoration(
              //当前颜色
              // color: Color.fromRGBO(19, 115, 183, 100),
              //设置图片
              image: DecorationImage(
                image: AssetImage('assets/images/circle.png'),
              ),
              //  shape: BoxShape.circle,
            ),
            todayTextStyle: TextStyle(
              fontSize: ScreenUtil().setSp(15),
              color: todyComplete ? Colors.transparent : Color(0xffFFCB03),
            ),
          ),
          startingDayOfWeek: StartingDayOfWeek.monday, //周一开始

          locale: geteLange(),
          availableGestures: AvailableGestures.none, //不要左右滑动
          headerVisible: false,

          firstDay: DateTime.utc(2010, 10, 16),
          lastDay: DateTime.utc(2200, 3, 14),
          focusedDay: DateTime.now(),
          calendarBuilders:
              CalendarBuilders(defaultBuilder: (context, day, focusedDay) {
            //  print("day是：${TimeUtils.gtTime6(day)}");
            //除今天的其他日期设置
            if (completeList.contains(day)) {
              //  if (completeList.contains(TimeUtils.gtTime6(day))) {
              return Container(
                width: size * 0.03,
                height: size * 0.03,
                margin: EdgeInsets.only(bottom: size * 0.008),
                child: Image.asset('assets/images/five_pointed_star.png',
                    fit: BoxFit.cover),
              );
            } else {
              return null;
            }
          }, todayBuilder: (context, day, focusedDay) {
            //今天的设置
            return todyComplete
                ? Container(
                    //今天完成
                    width: size * 0.03,
                    height: size * 0.03,
                    margin: EdgeInsets.only(bottom: size * 0.008),
                    child: Image.asset('assets/images/five_pointed_star.png',
                        fit: BoxFit.cover))
                : null;
            // : Container(  这里设置的话上面的 todayTextStyle就不起重要了，  反之相反。
            //     //今天没完成
            //     margin: EdgeInsets.only(bottom: ScreenUtil().setHeight(4)),
            //     width: ScreenUtil().setWidth(32),
            //     height: ScreenUtil().setWidth(32),
            //     decoration: BoxDecoration(
            //       image: DecorationImage(
            //           image: AssetImage('assets/images/circle.png'),
            //           fit: BoxFit.contain),
            //     ),
            //     alignment: Alignment.center,
            //     child: AutoSizeText(
            //       day.day.toString(),
            //       style: TextStyle(
            //         fontSize: ScreenUtil().setSp(14),
            //         color: Color(0Xfff4c809),
            //       ),
            //     ),
            //   );
          }),
        ),
      ],
    );
  }

  String geteLange() {
    String? value = SpUtils.getInstance()?.getString(AppConst.language);
    if (value == null) {
      return 'zh';
    } else {
      return value;
    }
  }
}
